//参考地址：https://segmentfault.com/a/1190000039806000?utm_source=sf-homepage-headline
import axios, { AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios'
import qs from "qs";

// create an axios instance
const service: AxiosInstance = axios.create({
  // baseURL: getMainAppUrl("mainAppUrl"), // url = base url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000, // request timeout
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
  },
  transformRequest: [
    function (data) {
      if (typeof data === 'object') return qs.stringify(data)
    },
  ],
})
// request interceptor
service.interceptors.request.use(
  (config:AxiosRequestConfig) => {
    if (localStorage.getItem(`qwt-wy-token`)) {
      config.headers["x-auth-token"] = localStorage.getItem(
        `qwt-wy-token`
      );
    }
    return config;
  },
  error => {
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data
    return res
  },
  (error) => {
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)
export default service 